package cn.yunyichina.reservation.controller.business;

import cn.yunyichina.reservation.component.pay.WechatPay;
import cn.yunyichina.reservation.component.pay.WechatPayService;
import cn.yunyichina.reservation.constant.HttpResponse;
import cn.yunyichina.reservation.constant.PayConst;
import cn.yunyichina.reservation.constant.PayType;
import cn.yunyichina.reservation.util.RequestUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by Lullaby on 2016/8/31.
 */
@RestController
@RequestMapping("pay")
public class PayController {

    @Resource
    private WechatPayService wechatPayService;

    /**
     * 支付统一入口
     *
     * @param request
     * @return
     */
    @PostMapping("unite")
    public HttpResponse unite(HttpServletRequest request) {
        HttpResponse httpResponse = new HttpResponse();
        Map<String, String> params = RequestUtil.getParameters(request);
        String clientIp = request.getRemoteAddr();
        params.put(PayConst.CLIENT_IP, clientIp);
        String payType = params.get(PayConst.PAY_TYPE);
        if (StringUtils.isNotBlank(payType)) {
            byte type = Byte.valueOf(payType);
            switch (type) {
                case PayType.WECHAT_PAY:
                    return wechat(params, httpResponse);
                case PayType.ALI_PAY:
                    httpResponse.failure("Alipay not implemented.");
                    break;
                case PayType.UNION_PAY:
                    httpResponse.failure("Union pay not implemented.");
                    break;
                case PayType.CREDITCARD_PAY:
                    httpResponse.failure("Credit card not implemented.");
                    break;
                default:
                    httpResponse.failure("Pay type not supported.");
            }
        } else {
            httpResponse.failure("Pay type required.");
        }
        return httpResponse;
    }

    private HttpResponse wechat(Map<String, String> params, HttpResponse httpResponse) {
        WechatPay pay = wechatPayService.pay(params);
        if (pay.isSuccess()) {
            httpResponse.setData(pay);
        } else {
            httpResponse.failure(pay.getMessage());
        }
        return httpResponse;
    }

}
